package org.javaboy.sms_login.config;

import org.javaboy.sms_login.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;

@Configuration
public class SecurityConfig {

    @Autowired
    UserService userService;

    @Bean
    SmsAuthenticationFilter smsAuthenticationFilter() {
        SmsAuthenticationFilter filter = new SmsAuthenticationFilter();
        filter.setFilterProcessesUrl("/login");
        filter.setAuthenticationSuccessHandler((req, resp, auth) -> {
            resp.getWriter().write(auth.getName());
        });
        filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());
        filter.setAuthenticationManager(authenticationManager());
        return filter;
    }

    @Bean
    AuthenticationManager authenticationManager() {
        SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider();
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        smsAuthenticationProvider.setUserDetailsService(userService);
        daoAuthenticationProvider.setUserDetailsService(userService);
        ProviderManager manager = new ProviderManager(daoAuthenticationProvider, smsAuthenticationProvider);
        return manager;
    }

    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        return web -> web.ignoring().requestMatchers("*.js");
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a.requestMatchers("/sendSms").permitAll().anyRequest().authenticated())
                .formLogin(f -> f.loginPage("/login.html").loginProcessingUrl("/login").permitAll())
                .csrf(c -> c.disable());
        http.addFilterBefore(smsAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}
